import React, { useState, useEffect } from 'react';
import '../css/create-event.css';
import { convertX, convertY, convertSize } from '../utils/responsive';
import EventTable from './EventTable';
import TempUseCard from './TempUseCard';

export interface EventFormData {
  title: string;
  startTime: string;
  endTime: string;
  process: string;
  description: string;
}

interface CreateEventProps {
  /** 组件是否可见 */
  visible?: boolean;
  /** 关闭组件的回调函数 */
  onClose?: () => void;
  /** 今日事件数据 */
  todayEvents?: string[][];
  /** 今日事件数据变化回调 */
  onTodayEventsChange?: (events: string[][]) => void;
  /** 提交事件的回调函数 */
  onSubmit?: (eventData: EventFormData) => void;
}

interface FormErrors {
  title?: string;
  startTime?: string;
  endTime?: string;
  process?: string;
}

/**
 * 创建事件的表单组件
 * 固定定位在x:22px, y:113px位置，宽度360px，高度1164px，层级z-index:200
 */
const CreateEvent: React.FC<CreateEventProps> = ({ visible = false, onClose, onSubmit }) => {
  if (!visible) return null;

  // 表单状态管理
  // 获取当前时间并格式化
  const getCurrentTime = (): string => {
    const now = new Date();
    return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
  };

  // 获取当前时间加一小时并格式化
  const getEndTime = (): string => {
    const now = new Date();
    now.setHours(now.getHours() + 1);
    return `${now.getHours().toString().padStart(2, '0')}:${now.getMinutes().toString().padStart(2, '0')}`;
  };

  const [formData, setFormData] = useState<EventFormData>({
    title: '',
    startTime: getCurrentTime(),
    endTime: getEndTime(),
    process: 'single',
    description: ''
  })
  const [errors, setErrors] = useState<FormErrors>({});
  const [isSubmitting, setIsSubmitting] = useState(false);
  const [currentDateTime, setCurrentDateTime] = useState('');
  const [showStartTimeNow, setShowStartTimeNow] = useState(true);
  const [showEndTimeNow, setShowEndTimeNow] = useState(true);

  // 简化后的事件数据格式
  const todayEvents = [
    ['12:10', '好好吃饭', '12:40', '150'],['12:10', '好好吃饭', '12:40', '150']
  ];

  useEffect(() => {
    const now = new Date();
    const formattedDate = `${now.getFullYear()}/${now.getMonth() + 1}/${now.getDate()} ${now.toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit', second: '2-digit' })}`;
    setCurrentDateTime(formattedDate);
  }, []);

  // 表单验证
  const validateForm = (): boolean => {
    const newErrors: FormErrors = {};

      if (!formData.title.trim()) {
      newErrors.title = '事件名称不能为空';
    } else if (formData.title.length > 50) {
      newErrors.title = '名称不能超过50个字符';
    }

    if (!formData.startTime) {
        newErrors.startTime = '请选择开始时间';
      } else {
        // 解析currentDateTime字符串为Date对象
        const [datePart, timePart] = currentDateTime.split(' ');
        const [year, month, day] = datePart.split('/').map(Number);
        const currentDateTimeObj = new Date(year, month - 1, day);
        
        // 提取时间部分
        const currentTimeStr = timePart.slice(0, 5); // 提取时:分
        const startTimeObj = new Date(`1970-01-01T${formData.startTime}`);
        const currentTimeObj = new Date(`1970-01-01T${currentTimeStr}`);
        
        if (startTimeObj > currentTimeObj) {
          newErrors.startTime = '开始时间不能大于新增事件显示时间';
        }
      }

    if (!formData.endTime) {
      newErrors.endTime = '请选择结束时间';
    } else if (formData.startTime && new Date(formData.endTime) <= new Date(formData.startTime)) {
      newErrors.endTime = '结束时间必须晚于开始时间';
    }

    if (!formData.process) {
      newErrors.process = '请选择任务归属进程';
    }

    setErrors(newErrors);
    return Object.keys(newErrors).length === 0;
  };

  // 表单提交处理
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();

    if (!validateForm()) return;
    if (!onSubmit) return;

    setIsSubmitting(true);
    try {
      await onSubmit(formData);
      onClose?.();
      // 重置表单
      setFormData({
        title: '',
        startTime: getCurrentTime(),
        endTime: getEndTime(),
        process: 'single',
        description: ''
      });
    } catch (error) {
      console.error('提交事件失败:', error);
    } finally {
      setIsSubmitting(false);
    }
  };

  // 输入变化处理
  const handleChange = (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));

    // 实时清除对应字段的错误
    if (errors[name as keyof FormErrors]) {
      setErrors(prev => ({
        ...prev,
        [name]: undefined
      }));
    }
  };

  return (
      <TempUseCard
        x={200}
        y={55}
        width={360}
        height='auto'
        useMaxHeight
        className="create-event-container"
      >
        <div className="create-event-content">
          <header className="create-event-header">
            <div className="header-content">
              <h2>新增事件</h2>
              <span className="current-date">{currentDateTime}</span>
            </div>
            <button className="btn-submit header-submit" onClick={handleSubmit} disabled={isSubmitting}>
              确认
            </button>
            <button className="create-event-close" onClick={onClose}>&times;</button>
          </header>
          <div className="create-event-body">
            <form onSubmit={handleSubmit} className="event-form">
              <div className="form-group horizontal-layout">
                <label htmlFor="event-title">事件名称 *</label>
                <input
                  type="text"
                  id="event-title"
                  name="title"
                  value={formData.title}
                  onChange={handleChange}
                  className={errors.title ? 'input-error' : ''}
                  maxLength={50}
                  disabled={isSubmitting}
                  placeholder="这儿是任务名"
                />
                {errors.title && <span className="error-message">{errors.title}</span>}
              </div>

              <div className="form-group time-group">
                <label>起止时间 *</label>
                <div className="time-inputs">
                  <div className="time-input-container">
                    <input
                      type="time"
                      name="startTime"
                      value={formData.startTime}
                      onChange={handleChange}
                      className={errors.startTime ? 'input-error' : ''}
                      disabled={isSubmitting}
                      onFocus={() => setShowStartTimeNow(false)}
                    />
                    <div className={`now-placeholder ${!showStartTimeNow ? 'hidden' : ''}`} onClick={() => {
                      setFormData(prev => ({...prev, startTime: getCurrentTime()}));
                      setShowStartTimeNow(false);
                    }}>NOW</div>
                  </div>
                  <span className="time-separator">至</span>
                  <div className="time-input-container">
                    <input
                      type="time"
                      name="endTime"
                      value={formData.endTime}
                      onChange={handleChange}
                      className={errors.endTime ? 'input-error' : ''}
                      disabled={isSubmitting}
                      onFocus={() => setShowEndTimeNow(false)}
                    />
                    <div className={`now-placeholder ${!showEndTimeNow ? 'hidden' : ''}`} onClick={() => {
                      setFormData(prev => ({...prev, endTime: getCurrentTime()}));
                      setShowEndTimeNow(false);
                    }}>NOW</div>
                  </div>
                </div>
                {(errors.startTime || errors.endTime) && <span className="error-message">{errors.startTime || errors.endTime}</span>}
              </div>

              <div className="form-group">
                <label htmlFor="event-process">任务归属进程 *</label>
                <select
                  id="event-process"
                  name="process"
                  value={formData.process}
                  onChange={handleChange}
                  className={errors.process ? 'input-error' : ''}
                  disabled={isSubmitting}
                >
                  <option value="">请选择进程</option>
                  <option value="single">单次</option>
                  <option value="diet">饮食习惯养成</option>
                  <option value="exercise">运动计划</option>
                  <option value="study">学习任务</option>
                  <option value="work">工作项目</option>
                </select>
                {errors.process && <span className="error-message">{errors.process}</span>}
              </div>

              <div className="form-group description-group">
                <label htmlFor="event-description">事件说明</label>
                <textarea
                    id="event-description"
                    name="description"
                    value={formData.description}
                    onChange={handleChange}
                    rows={3}
                    disabled={isSubmitting}
                    placeholder="这里写一些备注提醒"
                  />
              </div>
            </form>
          </div>

          <div className="today-events">
            <h3>今日事件</h3>
            <div className="event-list">
              <EventTable events={todayEvents} />
              <table>
                <tr>
                  <th className='tds-white'>Firstname</th>
                  <th></th>
                </tr>
              </table>
            </div>
            <div className="list-end">The end</div>
          </div>
        </div>
      </TempUseCard>
    );
};

export default CreateEvent;
